package logic

import (
	"context"
	"fmt"
	"product666/model/mysql"
	"product666/model/redis"

	"product666/userrpc/internal/svc"
	"product666/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdataLogic {
	return &UpdataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdataLogic) Updata(in *userrpc.UpdataRequest) (*userrpc.UpdataResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("SendSmsupdata" + in.Username)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("短信验证码发送失败")
	}

	var finduser mysql.User
	mysql.DB.Where("id=?", in.Id).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("用户还未注册")
	}
	if finduser.Password != in.Password {
		return nil, fmt.Errorf("密码输入错误")
	}
	if finduser.Password == in.Newpasss {
		return nil, fmt.Errorf("新密码不可与原密码相同")
	}
	if in.Newpass != in.Newpasss {
		return nil, fmt.Errorf("两次密码输入不一样")
	}
	finduser.Password = in.Newpass
	mysql.DB.Updates(&finduser)

	return &userrpc.UpdataResponse{Id: int64(finduser.ID)}, nil
}
